//
//  CaiWuMingXiViewController.m
//  1243
//
//  Created by 我的 on 16/4/7.
//  Copyright © 2016年 1243. All rights reserved.
//

#import "CaiWuMingXiViewController.h"
#import "CaiWuHeaderCell.h"
#import "CaiWuFirstCell.h"
#import "CaiWuSecondCell.h"
#import "AllBtnViewController.h"
#import "DateViewController.h"
#import "NetWorkTools.h"
#import "ReadLoginData.h"
#import "SVProgressHUD.h"


#define HEADER_HEIGHT 50
@interface CaiWuMingXiViewController ()<UITableViewDelegate, UITableViewDataSource, UIAlertViewDelegate>
@property (nonatomic, strong) CaiWuHeaderCell *caiwuHeader;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, copy)NSString *STR;
@property (nonatomic, copy) NSString *string;
@property (nonatomic, strong) DateViewController *dateVC;
@property (nonatomic, strong)NSMutableArray *dataArr;
@property (nonatomic, strong) AllBtnViewController *allBtnVC;

@property(nonatomic,strong) NSArray *totalArray;

@property (nonatomic, assign) NSInteger pageIndex;

@property (nonatomic, strong) NSString *UseMoney;

@end

@implementation CaiWuMingXiViewController

- (NSMutableArray *)dataArr {
    
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.STR = @"0";
    self.pageIndex = 1;
    
    [self setHeaderView];
    self.view.backgroundColor = [UIColor lightGrayColor];
    self.title = @"财务明细";
//    self.navigationController.navigationBar.translucent = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    self.tableView.tableFooterView = [UIView new];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"CaiWuFirstCell" bundle:nil] forCellReuseIdentifier:@"FirstCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"CaiWuSecondCell" bundle:nil] forCellReuseIdentifier:@"SecondCell"];
    
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    self.tableView.mj_footer.automaticallyHidden = YES;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeAllBtnTitle:) name:@"AllBtnNoti" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeDateBtnTitle:) name:@"changBtnSelected" object:nil];
    
    //默认请求
    [self data:@"0"];
    [self totalData:@"0"];
}

- (void)loadMoreData {
    [self loadNewData:self.STR];
    [self newTotalData:self.STR];
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    [SVProgressHUD dismiss];
    [self.allBtnVC backAllBtnView];
}

#pragma mark - Noti

- (void)changeAllBtnTitle:(NSNotification *)noti {
    NSString *str = noti.userInfo[@"AllBtnTitle"];
    [self.caiwuHeader.allBtn setTitle:str forState:UIControlStateNormal];
    self.caiwuHeader.allBtn.selected = NO;
    self.STR = noti.userInfo[@"AllBtnTag"];
    if ([self.STR isEqualToString:@"7"]) {
        self.string = self.STR;
        self.STR = @"0";
        [self data:@"7"];
        [self totalData:@"7"];
    } else {
        if ([self.STR isEqualToString:@"8"]) {
            self.string = self.STR;
            self.STR = @"12";
            [self data:@"12"];
            [self totalData:@"12"];
        } else if ([self.STR isEqualToString:@"2"]) {
            self.string = self.STR;
            self.STR = @"11";
            [self data:@"11"];
            [self totalData:@"11"];
        } else {
            [self data:self.STR];
            [self totalData:self.STR];
        }
        self.string = @"";
    }
    
    NSIndexPath *firstIndex = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.tableView selectRowAtIndexPath:firstIndex animated:YES scrollPosition:UITableViewScrollPositionTop];
}

- (void)changeDateBtnTitle:(NSNotification *)noti {
    self.caiwuHeader.startBtn.selected = NO;
    self.caiwuHeader.endBtn.selected = NO;
    NSString *str = noti.userInfo[@"SelectedTime"];
    str = [str substringToIndex:11];
    NSInteger integer = [noti.userInfo[@"BtnTag"] integerValue];
    if (integer == 10000) {
        [self.caiwuHeader.endBtn setTitle:[NSString stringWithFormat:@"结束日期"] forState:UIControlStateNormal];
        self.caiwuHeader.endLabel.text = [NSString stringWithFormat:@"%@", str];
        self.caiwuHeader.endBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 20, 0);
        self.caiwuHeader.endBtn.titleLabel.textColor = [UIColor blackColor];
        self.caiwuHeader.endBtn.titleLabel.font = [UIFont systemFontOfSize:11];
        [self data:self.STR];
        [self totalData:self.STR];
    } else {
        [self.caiwuHeader.startBtn setTitle:[NSString stringWithFormat:@"起始日期"] forState:UIControlStateNormal];
        self.caiwuHeader.startLabel.text = [NSString stringWithFormat:@"%@", str];
        self.caiwuHeader.startBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 20, 0);
        self.caiwuHeader.startBtn.titleLabel.textColor = [UIColor blackColor];
        self.caiwuHeader.startBtn.titleLabel.font = [UIFont systemFontOfSize:11];
    }
    //    NSLog(@"%@", str);
}


#pragma mark - headerBtn fun

- (void)clickAllBtn {
    self.allBtnVC = [AllBtnViewController sharedAllBtnVC];
//    NSLog(@"~%d", self.caiwuHeader.allBtn.selected);
    if (self.caiwuHeader.allBtn.selected == YES) {
        // 隐藏
        [self.allBtnVC backAllBtnView];
        self.caiwuHeader.allBtn.selected = NO;
    } else {
        //  显示
        [self.allBtnVC loadAllBtnView];
        
        self.caiwuHeader.allBtn.selected = YES;
    }
    
    
    
}

- (void)clickChooseDate:(UIButton *)btn {
    
    if (btn.selected == YES) {
        [self.dateVC backDateView:btn.tag];
        btn.selected = NO;
    } else {
        [self.dateVC showDateView:btn.tag];
        btn.selected = YES;
    }
}

- (void)loadNewData:(NSString * )inter {
    //    self.dataArr = [NSMutableArray array];
    //    NSString *stringInt = [NSString stringWithFormat:@"%d",inter];
    
    self.pageIndex ++;
    
    NSDictionary *params = [ReadLoginData readLoginData];
    
    NSDictionary *dic= @{
                         @"UserId":[params objectForKey:@"Number"],
                         @"Type":[self.STR isEqualToString:@"7"] ? @"0" : self.STR,
                         @"Stime":self.caiwuHeader.startLabel.text,
                         @"Etime":self.caiwuHeader.endLabel.text,
                         @"PageIndex":[NSString stringWithFormat:@"%ld", self.pageIndex],
                         @"PageSize":@"10"
                         };
    
    [SVProgressHUD show];
    [[NetWorkTools  sharedNetWorkTools] objectWithURLDict:dic AndMenthodName:@"MONEYUSERLIST" completeBlock:^(id object) {
        
        [SVProgressHUD dismiss];
        [self.tableView.mj_footer endRefreshing];
        if ([object[@"Message"] isEqualToString:@"查询失败"]) {
            self.tableView.mj_footer.hidden = YES;
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"没有更多数据" delegate: self cancelButtonTitle:@"确定" otherButtonTitles: nil, nil];
            alert.tag = 12345;
            [alert show];
            return ;
        }
//        NSLog(@"~~%@",object);
        NSString *srt = [object objectForKey:@"BackData"];
        NSArray *arr = [NetWorkTools arrayWithJsonString:srt];
        [self.dataArr addObjectsFromArray:arr];
        [self.tableView reloadData];
    }];
    
    NSLog(@"加载更多时：%@", inter);
}

- (void)data:(NSString * )inter {
    
    self.pageIndex = 1;
    
    NSDictionary *params = [ReadLoginData readLoginData];
    
    NSDictionary *dic= @{
                         @"UserId":[params objectForKey:@"Number"],
                         @"Type":inter,
                         @"Stime":self.caiwuHeader.startLabel.text,
                         @"Etime":self.caiwuHeader.endLabel.text,
                         @"PageIndex":@"1",
                         @"PageSize":@"10"
                         };
    
    [SVProgressHUD show];
    [[NetWorkTools  sharedNetWorkTools] objectWithURLDict:dic AndMenthodName:@"MONEYUSERLIST" completeBlock:^(id object) {
//     NSLog(@"~~%@",object);
//        NSArray *array = self.dataArr;
        [self.dataArr removeAllObjects];
        [SVProgressHUD dismiss];
        NSString *srt = [object objectForKey:@"BackData"];
        NSArray *arr = [NetWorkTools arrayWithJsonString:srt];
        [self.dataArr addObjectsFromArray:arr];
//        NSLog(@"%@", self.dataArr);
        [self.tableView reloadData];
        
        
    }];
    NSLog(@"第一次加载时：%@", inter);

}

- (void)newTotalData:(NSString * )inter {
    //    self.dataArr = [NSMutableArray array];
    //    NSString *stringInt = [NSString stringWithFormat:@"%d",inter];
    
    NSDictionary *params = [ReadLoginData readLoginData];
    
    NSDictionary *dic= @{
                         @"UserId":[params objectForKey:@"Number"],
                         @"Type":inter,
                         @"Stime":self.caiwuHeader.startLabel.text,
                         @"Etime":self.caiwuHeader.endLabel.text,
                         @"PageIndex":[NSString stringWithFormat:@"%ld", self.pageIndex],
                         @"PageSize":@"10"
                         };
    
    [SVProgressHUD show];
    [[NetWorkTools  sharedNetWorkTools] objectWithURLDict:dic AndMenthodName:@"MONEYUSERLISTMONEYALL" completeBlock:^(id object) {
//        NSLog(@"~~%@",object);
        
        NSString *srt = [object objectForKey:@"BackData"];
        NSArray *arr = [NetWorkTools arrayWithJsonString:srt];
        //        [self.totalArray addObjectsFromArray:arr];
        self.totalArray = arr;
        if (self.totalArray[0][@"UseMoney"] != [NSNull null]) {
            self.UseMoney = [NSString stringWithFormat:@"%.2f", [self.totalArray[0][@"UseMoney"] floatValue] + [self.UseMoney floatValue]];
        }
        [self.tableView reloadData];
    }];
    
}

//0 39800.0000  234 7

//总计数请求
- (void)totalData:(NSString * )inter {
    
    self.pageIndex = 1;
    
    NSDictionary *params = [ReadLoginData readLoginData];
    
    NSDictionary *dic= @{
                         @"UserId":[params objectForKey:@"Number"],
                         @"Type":inter,
                         @"Stime":self.caiwuHeader.startLabel.text,
                         @"Etime":self.caiwuHeader.endLabel.text,
                         @"PageIndex":@"1",
                         @"PageSize":@"10"
                         };
    
    [SVProgressHUD show];
    [[NetWorkTools  sharedNetWorkTools] objectWithURLDict:dic AndMenthodName:@"MONEYUSERLISTMONEYALL" completeBlock:^(id object) {
//        NSLog(@"~~%@",object);

        NSString *srt = [object objectForKey:@"BackData"];
        NSArray *arr = [NetWorkTools arrayWithJsonString:srt];
//        [self.totalArray addObjectsFromArray:arr];
        self.totalArray = arr;
        if (self.totalArray[0][@"UseMoney"] != [NSNull null]) {
            self.UseMoney = [NSString stringWithFormat:@"%.2f", [self.totalArray[0][@"UseMoney"] floatValue]];
        } else {
            self.UseMoney = @"0.00";
        }
        [self.tableView reloadData];
    }];
    
}

//{"Number":661313,"S_Number":7,"U_Number":1002,"UserName":"陈立恩","UseMoney":26.0000,"UseMark":"获取红包 26.00元","UseTime":"2016-05-10T17:52:45","Curr_Money":5183.0100,"Leave":0,"Result":"红包","Remark":"","OrdeNum":17125,"ToUserNumber":1002}


- (CaiWuHeaderCell *)caiwuHeader {
    
    if (!_caiwuHeader) {
        _caiwuHeader = [CaiWuHeaderCell loadCaiWuHeaderView];
        _caiwuHeader.frame = CGRectMake(0, 64, WIDTH, HEADER_HEIGHT);
    }
    return _caiwuHeader;
}

- (DateViewController *)dateVC {
    
    if (!_dateVC) {
        _dateVC = [[DateViewController alloc] init];
    }
    return _dateVC;
}

- (UITableView *)tableView {
    
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.caiwuHeader.frame), WIDTH, HEIGHT- HEADER_HEIGHT - 64) style:UITableViewStyleGrouped];
        [self.view addSubview:_tableView];
    }
    return _tableView;
}



- (void)setHeaderView {
    
    [self setLeftViewWithTextField:self.caiwuHeader.searchTextField imageName:@"nav_2"];
    [self.view addSubview:self.caiwuHeader];
    
    [self.caiwuHeader.allBtn addTarget:self action:@selector(clickAllBtn) forControlEvents:UIControlEventTouchUpInside];
    self.caiwuHeader.allBtn.selected = NO;
    
    [self.caiwuHeader.startBtn addTarget:self action:@selector(clickChooseDate:) forControlEvents:UIControlEventTouchUpInside];
    self.caiwuHeader.startBtn.tag = 10001;
    self.caiwuHeader.startBtn.selected = NO;
    
    [self.caiwuHeader.endBtn addTarget:self action:@selector(clickChooseDate:) forControlEvents:UIControlEventTouchUpInside];
    self.caiwuHeader.endBtn.tag = 10000;
    self.caiwuHeader.endBtn.selected = NO;
}

/**
 *  给UITextField设置右侧的图片
 *
 *  @param textField UITextField
 *  @param imageName 图片名称
 */

-(void)setLeftViewWithTextField:(UITextField *)textField imageName:(NSString *)imageName{
    
    UIImageView *rightView = [[UIImageView alloc]init];
    
    rightView.image = [UIImage imageNamed:imageName];
    rightView.frame = CGRectMake(0, 0, CGRectGetHeight(textField.frame), CGRectGetHeight(textField.frame));
    rightView.contentMode = UIViewContentModeCenter;
    
    textField.rightView = rightView;
    textField.rightViewMode = UITextFieldViewModeAlways;
    textField.backgroundColor = [UIColor clearColor];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 1) {
        
        return self.dataArr.count;
    }
    return 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        CaiWuFirstCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FirstCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (self.totalArray.count) {
            NSDictionary *dic = self.totalArray[indexPath.row];
            if (dic[@"UseMoney"] != [NSNull null]) {

                cell.zongJiLabel.text = self.UseMoney;
            } else {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"暂无数据" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                alert.tag = 1234;
            //   [alert show];
                 cell.zongJiLabel.text =@"0";
            }

        }
//        NSLog(@"cell.zongJiLabel.text%@",cell.zongJiLabel.text);
        
        return cell;
    } else {
        CaiWuSecondCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SecondCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        //判断是不是积分奖励
        if ([self.string isEqualToString:@"7"]) {
            NSDictionary *dic = self.dataArr[indexPath.row];
            cell.titleLabel.text = [NSString stringWithFormat:@"当前:%@", dic[@"Curr_Money"]];
            cell.moneyLabel.text =[NSString stringWithFormat:@"奖励:%@",dic[@"UseMoney"]];
            cell.detailLabel.text = [dic[@"UseTime"] stringByReplacingOccurrencesOfString:@"T" withString:@" "];
            cell.timeLabel.text =[dic[@"UseTime"] stringByReplacingOccurrencesOfString:@"T" withString:@" "];
        }else{
            
            NSDictionary *dic = self.dataArr[indexPath.row];
            cell.titleLabel.text = dic[@"Result"];
            cell.moneyLabel.text =[NSString stringWithFormat:@"%@",dic[@"UseMoney"]];
            cell.detailLabel.text = dic[@"UseMark"];
            cell.detailLabel.numberOfLines = 0;
            cell.timeLabel.text =[dic[@"UseTime"] stringByReplacingOccurrencesOfString:@"T" withString:@" "];
            
        }
        
        return cell;
    }
}

#pragma mark - TableView delegate 

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 1) {
        return 80;
    }
    return 60;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 1) {
        return 0.01;
    }
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    if (alertView.tag == 12345) {
//        [self.navigationController popViewControllerAnimated:YES];
        self.tableView.mj_footer.hidden = YES;
    }
}

@end
